package dao;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: HP
 * Date: 2023 -06 -25
 * Time: 20:17
 */

import bean.Dish;
import bean.Order;
import bean.User;
import util.DBUtil;
import util.OrderSystemException;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 1.新增
 * 2.查询所有订单
 * 3.查询用户订单
 * 4.查询订单详细信息
 * 5.修改订单状态
 */
public class OrderDao {
    public void add(Order order) throws OrderSystemException {
        addOrderUser(order);
        addOrderDish(order);
    }

    public void addOrderUser(Order order) throws OrderSystemException {
        Connection connection = DBUtil.getConnection();
        String sql = "insert into order_user values(null,?,now(),0)";
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            statement.setInt(1, order.getUserId());
            int ret = statement.executeUpdate();
            if (ret != 1) {
                throw new OrderSystemException("插入订单用户失败");
            }
            resultSet = statement.getGeneratedKeys();
            if (resultSet.next()) {
                order.setOrderId(resultSet.getInt(1));//获取第一个自增列生成值
            }
            System.out.println("订单用户插入成功");
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(connection, statement, resultSet);
        }
    }

    public void addOrderDish(Order order) throws OrderSystemException {
        Connection connection = DBUtil.getConnection();
        String sql = "insert into order_dish values(?,?)";
        PreparedStatement statement = null;
        try {
            statement = connection.prepareStatement(sql);
            List<Dish> dishes = order.getDishes();
            for (Dish dish : dishes) {
                statement.setInt(1, order.getOrderId());
                statement.setInt(2, dish.getDishId());
                statement.addBatch();//给sql新增一个片端
            }
            connection.setAutoCommit(false);
            statement.executeBatch();//执行sql
            connection.commit();//commit执行
            System.out.println("订单菜品插入成功");
        } catch (SQLException e) {
            e.printStackTrace();
            deleteOrderUser(order.getOrderId());//将前一步插入给回滚
        } finally {
            DBUtil.close(connection, statement, null);
        }
    }

    public void deleteOrderUser(int orderId) throws OrderSystemException {
        Connection connection = DBUtil.getConnection();
        String sql = "delete from order_user where orderId=?";
        PreparedStatement statement = null;
        try {
            statement = connection.prepareStatement(sql);
            statement.setInt(1, orderId);
            int ret = statement.executeUpdate();
            if (ret != 1) {
                throw new OrderSystemException("删除订单用户失败-回滚失败");
            }
            System.out.println("回滚成功");
        } catch (SQLException e) {
            e.printStackTrace();
            throw new OrderSystemException("回滚失败");
        } finally {
            DBUtil.close(connection, statement, null);
        }
    }
    //查询所有订单
    public List<Order> selectAllOders() throws OrderSystemException {
        List<Order> orders = new ArrayList<>();
        Connection connection = DBUtil.getConnection();
        String sql = "select * from order_user";
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery();
            while (resultSet.next()) {
                Order order = new Order(resultSet.getInt("orderId"),
                        resultSet.getInt("userId"),
                        resultSet.getTimestamp("time"),
                        resultSet.getInt("isDone"));
                orders.add(order);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new OrderSystemException("查询所有订单用户失败");
        } finally {
            DBUtil.close(connection, statement, resultSet);
        }
        return orders;
    }
    //查询用户所有订单 by userid
    public List<Order> selectOrdersByUserId(int userId) throws OrderSystemException {
        List<Order> orders = new ArrayList<>();
        Connection connection = DBUtil.getConnection();
        String sql = "select * from order_user where userId=?";
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            statement = connection.prepareStatement(sql);
            statement.setInt(1, userId);
            resultSet = statement.executeQuery();
            while (resultSet.next()) {
                Order order = new Order(resultSet.getInt("orderId"),
                        resultSet.getInt("userId"),
                        resultSet.getTimestamp("time"),
                        resultSet.getInt("isDone"));
                orders.add(order);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new OrderSystemException("查询用户订单用户失败");
        } finally {
            DBUtil.close(connection, statement, resultSet);
        }
        return orders;
    }
    //查询订单详情
    public Order selectOrderDetail(int orderId) throws OrderSystemException {
        Order order=selectByOrderId(orderId);
        List<Integer> dishIds=selectDishIds(orderId);
        List<Dish> dishes = new ArrayList<>();
        DishDao dishDao = new DishDao();
        for (Integer dishId : dishIds) {
            Dish dish = dishDao.selectById(dishId);
            dishes.add(dish);
        }
        order.setDishes(dishes);
        return order;
    }
    //查询order_user by orderId
    public Order selectByOrderId(int orderId) throws OrderSystemException {
        Connection connection = DBUtil.getConnection();
        String sql = "select * from order_user where orderId=?";
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            statement = connection.prepareStatement(sql);
            statement.setInt(1, orderId);
            resultSet = statement.executeQuery();
            if (resultSet.next()) {
                Order order = new Order(resultSet.getInt("orderId"),
                        resultSet.getInt("userId"),
                        resultSet.getTimestamp("time"),
                        resultSet.getInt("isDone"));
                return order;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new OrderSystemException("按订单id查询订单用户失败");
        } finally {
            DBUtil.close(connection, statement, resultSet);
        }
        return null;
    }
    //查询对应订单相关的菜品id
    public List<Integer> selectDishIds(int orderId) throws OrderSystemException {
        List<Integer> dishIds=new ArrayList<>();
        Connection connection = DBUtil.getConnection();
        String sql = "select * from order_dish where orderId=?";
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            statement = connection.prepareStatement(sql);
            statement.setInt(1, orderId);
            resultSet = statement.executeQuery();
            while (resultSet.next()) {
                dishIds.add(resultSet.getInt("dishId"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new OrderSystemException("按订单id查询订单相关菜品id失败");
        } finally {
            DBUtil.close(connection, statement, resultSet);
        }
        return dishIds;
    }
    public void changeState(int orderId,int isDone)throws OrderSystemException{
        Connection connection = DBUtil.getConnection();
        String sql = "update order_user set isDone=? where orderId=?";
        PreparedStatement statement = null;
        try {
            statement = connection.prepareStatement(sql);
            statement.setInt(1, isDone);
            statement.setInt(2,orderId);
            int ret = statement.executeUpdate();
           if(ret!=1){
               throw new OrderSystemException("订单状态修改失败");
           }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new OrderSystemException("订单状态修改失败");
        } finally {
            DBUtil.close(connection, statement, null);
        }
    }
}
